package com.zlt.invocation;

import com.zlt.annotation.Transactional;
import com.zlt.util.SqlUtil;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class TansactionInvocation implements InvocationHandler {

    private Object target;

    public TansactionInvocation(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        boolean transaction = method.isAnnotationPresent(Transactional.class);
    
        // 当方法上存在 @Transactional 注解时，才开启事务
        if (transaction) {
            SqlUtil.beginTransaction();
        }
    
        Object result = null;
    
        try {
            result = method.invoke(target, args);
            if (transaction) {
                // 无异常，提交事务
                SqlUtil.commit();
            }
        } catch (RuntimeException e) {
            if (transaction) {
                // 有异常，回滚事务
                SqlUtil.rollback();
            }
        } finally {
            // 释放当前数据库连接，将当前数据库连接放回连接池
            SqlUtil.close(null, null, SqlUtil.getCurrentConnection());
        }
    
    
        return result;
    }
}
